﻿using Core.Utility.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Extendsions.Validation
{
    /// <summary>
    /// 验证助手类，针对数据模型使用 <see cref="System.ComponentModel.DataAnnotations"/> 特性进行数据有效性校验的助手类
    /// </summary>
    public static class ValidatetionExtensions
    {
        /// <summary>
        /// 数据有效验证结果
        /// </summary>
        /// <param name="value"></param>
        /// <returns>ValidationExtensionsResult.IsValid：true:有效,false:无效</returns>
        public static ValidationExtensionsResult ValidResult(this object value)
        {
            ValidationExtensionsResult result = new ValidationExtensionsResult();
            try
            {
                var validationContext = new ValidationContext(value);
                var results = new List<ValidationResult>();
                var isValid = Validator.TryValidateObject(value, validationContext, results, true);

                if (!isValid)
                {
                    result.IsValid = false;
                    result.ErrorMembers = new List<ErrorMember>();
                    foreach (var item in results)
                    {
                        result.ErrorMembers.Add(new ErrorMember()
                        {
                            ErrorMessage = item.ErrorMessage,
                            ErrorMemberName = item.MemberNames.FirstOrDefault()
                        });
                    }
                }
                else
                {
                    result.IsValid = true;
                }
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.ErrorMembers = new List<ErrorMember>();
                result.ErrorMembers.Add(new ErrorMember()
                {
                    ErrorMessage = ExceptionMessageHelper.Output(ex),
                    ErrorMemberName = "Internal error"
                });

            }
            return result;
        }
    }
}
